#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<queue>
#include<string>
#include<unordered_set>
using namespace std;
class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> as(wordList.begin(), wordList.end());
        unordered_set<string> aq;
        int ret = 1;
        if (!as.count(endWord))
        {
            return 0;
        }
        queue<string> w;
        w.push(beginWord);
        aq.insert(beginWord);
        while (w.size())
        {
            ret++;
            int sz = w.size();
            while (sz--)
            {
                string t = w.front();
                w.pop();
                for (int i = 0; i < t.size(); i++)
                {
                    string tmp = t;
                    for (char j = 'a'; j <= 'z'; j++)
                    {
                        tmp[i] = j;
                        if (!aq.count(tmp) && as.count(tmp))
                        {
                            if (tmp == endWord)
                            {
                                return ret;
                            }
                            w.push(tmp);
                            aq.insert(tmp);
                        }
                    }
                }
            }
        }
        return 0;
    }
};